package com.qf.czh.vhr.config;

import com.qf.czh.vhr.Service.MenuService;
import com.qf.czh.vhr.entity.Menu;
import com.qf.czh.vhr.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;
@Component
public class MyFilter implements FilterInvocationSecurityMetadataSource {
    @Autowired
    MenuService menuService;
    AntPathMatcher antPathMatcher = new AntPathMatcher();
    //目的就是找到当前请求 所需的角色名list
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation invocation = (FilterInvocation) object;
        //获取当前请求
        String requestUrl = invocation.getRequestUrl();
        //查出所有菜单的路径关联角色表中的id,即全部路径每个所需要的角色list.
        List<Menu> menus = menuService.getAllMenus();
        //循环每个路径都与当前请求路径比对下,找出当前路径所需要的角色list
        for (Menu menu:menus) {
            //如果比对上了,当前路径在菜单表中路径字段找到.

            if (antPathMatcher.match(menu.getUrl(), requestUrl)){ //matcher对象要自己new
                //取出该路径所需的角色list
                List<Role> roles = menu.getRoles();
                //将角色list放入数组,因为后边createlist方法要传如数组.
                String[] arr = new String[roles.size()];
                //新建一个与list同样大小的数组.因为后边createlist方法要传如数组.
                for (int i = 0; i < roles.size(); i++) {
                    //将角色list逐个拿出角色名,放入数组,
                    arr[i] = roles.get(i).getName();
                }
                //将该角色名字数组传入,并发挥
                return SecurityConfig.createList(arr);
            }
        }
        //如果都没匹配上,即该请求不在菜单路径中,也就没有任何需要的角色,就定义一个角色返回.
        return SecurityConfig.createList("ROLE_LOGIN");

    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null; //不变,返回null就行
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true; //直接fanhuitrue
     }
}
